package org.ngmj.server.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.ngmj.message.LoginRequestMessage;
import org.ngmj.message.LoginResponseMessage;
import org.ngmj.server.service.UserService;
import org.ngmj.server.service.UserServiceFactory;
import org.ngmj.server.session.SessionFactory;

@Slf4j
@ChannelHandler.Sharable
public class LoginRequestHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage loginRequestMessage) throws Exception {
        log.info("{}", loginRequestMessage);
        UserService userService = UserServiceFactory.getUserService();
        if (userService.login(loginRequestMessage.getUsername(), loginRequestMessage.getPassword())) {
            SessionFactory.getSession().bind(ctx.channel(), loginRequestMessage.getUsername());
            ctx.writeAndFlush(new LoginResponseMessage(true, "登录成功"));
        } else {
            ctx.writeAndFlush(new LoginResponseMessage(false, "用户名或密码错误"));
        }
    }
}
